package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.hjq.http.listener.HttpCallback;
import com.hjq.umeng.UmengClient;
import com.qiantu.api.entity.SmsBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppConfig;
import com.qiantu.phone.widget.CursorFrameTextView;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class Captcha1Activity extends AppActivity {

    private static final String INTENT_KEY_IN_PHONE = "phone";

    //预留新手机号页面跳转过来完成手机号更换
    @Log
    public static void start(Context context, String phone, String originalSmsId, String smsId, int type) {
        Intent intent = new Intent(context, Captcha1Activity.class);
        intent.putExtra(INTENT_KEY_IN_PHONE, phone);
        intent.putExtra("type", type);
        intent.putExtra("originalSmsId", originalSmsId);
        intent.putExtra("smsId", smsId);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }


    //预留新手机号页面跳转过来提交申诉
    public static void start(Context context, String newPhone, String oldPhone, String description, String accountInfo, String smsId, int type) {
        Intent intent = new Intent(context, Captcha1Activity.class);
        intent.putExtra(INTENT_KEY_IN_PHONE, newPhone);
        intent.putExtra("type", type);
        intent.putExtra("oldPhone", oldPhone);
        intent.putExtra("description", description);
        intent.putExtra("accountInfo", accountInfo);
        intent.putExtra("smsId", smsId);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private EditText editSmsCode;
    private CursorFrameTextView tvSmsCode1;
    private CursorFrameTextView tvSmsCode2;
    private CursorFrameTextView tvSmsCode3;
    private CursorFrameTextView tvSmsCode4;
    private TextView tvCountDown;
    private TextView btnSubmit;
    private CursorFrameTextView.OnPasteCallback mOnPasteCallback;
    private Handler mHandler;
    private String phone;
    private int countDownTime = 60;
    //1提交申诉 2验证手机号 3更换手机号
    private int type;
    private String originalSmsId;
    private String smsId;
    String smsType;

    @Override
    protected int getLayoutId() {
        return R.layout.captcha1_activity;
    }

    @Override
    protected void initView() {
        UmengClient.init(AppApplication.getInstance(), AppConfig.isLogEnable());
        phone = getIntent().getStringExtra(INTENT_KEY_IN_PHONE);
        smsId = getIntent().getStringExtra("smsId");
        originalSmsId = getIntent().getStringExtra("originalSmsId");
        type = getIntent().getIntExtra("type", 0);
        TextView mPhoneNotAvailable = findViewById(R.id.tv_phone_not_available);
        mPhoneNotAvailable.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        mPhoneNotAvailable.getPaint().setAntiAlias(true);//抗锯齿
        TextView tvPhone = findViewById(R.id.tv_phone);
        tvPhone.setText(phone);
        editSmsCode = findViewById(R.id.edit_sms_code);
        tvSmsCode1 = findViewById(R.id.tv_sms_code_1);
        tvSmsCode2 = findViewById(R.id.tv_sms_code_2);
        tvSmsCode3 = findViewById(R.id.tv_sms_code_3);
        tvSmsCode4 = findViewById(R.id.tv_sms_code_4);
        tvCountDown = findViewById(R.id.tv_count_down);
        btnSubmit = findViewById(R.id.btn_submit);
        switch (type){
            case 1:
                btnSubmit.setText("提交申诉");
                mPhoneNotAvailable.setVisibility(View.GONE);
                break;
            case 2:
                smsType = "changeMobile1_boyun";
                btnSubmit.setText("下一步");
                mPhoneNotAvailable.setVisibility(View.VISIBLE);
                break;
            case 3:
                smsType = "changeMobile2_boyun";
                btnSubmit.setText("完成更换");
                mPhoneNotAvailable.setVisibility(View.GONE);
                break;
        }
        setOnClickListener(tvSmsCode1, tvSmsCode2, tvSmsCode3, tvSmsCode4, tvCountDown, mPhoneNotAvailable, btnSubmit);
        initCodeView();
        if(mHandler == null){
            mHandler = new Handler();
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showTvSmsCodeSoftInput();
            }
        }, 200);
        startCountDown();
    }

    private void startCountDown(){
        countDownTime = 60;
        mHandler.post(countDownRunnable);
    }

    private Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {
            countDownTime--;
            tvCountDown.setText(countDownTime + getString(R.string.get_again_count_down));
            tvCountDown.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
            tvCountDown.setEnabled(false);
            if(countDownTime == 0){
                tvCountDown.setText(R.string.get_again);
                tvCountDown.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                tvCountDown.setEnabled(true);
                return;
            }
            mHandler.postDelayed(countDownRunnable, 996);
        }
    };

    private void initCodeView(){
        editSmsCode.setText(null);
        tvSmsCode1.setSelected(true);
        if (mOnPasteCallback == null) {
            mOnPasteCallback = new CursorFrameTextView.OnPasteCallback() {
                @Override
                public void onPaste(String data) {
                    if (data == null){
                        return;
                    }
                    if (data.length()>4){
                        data = data.substring(0, 4);
                    }
                    editSmsCode.setText(data);
                    editSmsCode.setSelection(data.length());
                }
            };
        }
        tvSmsCode1.setOnPasteCallback(mOnPasteCallback);
        tvSmsCode2.setOnPasteCallback(mOnPasteCallback);
        tvSmsCode3.setOnPasteCallback(mOnPasteCallback);
        tvSmsCode4.setOnPasteCallback(mOnPasteCallback);
        editSmsCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for (int i = 0; i < 4; i++) {
                    int currentLength = s.length();
                    String s1 = i < currentLength ? String.valueOf(s.charAt(i)) : "";
                    switch (i) {
                        case 0:
                            tvSmsCode1.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode1.setSelected(true);
                            } else {
                                tvSmsCode1.setSelected(false);
                            }
                            break;
                        case 1:
                            tvSmsCode2.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode2.setSelected(true);
                            } else {
                                tvSmsCode2.setSelected(false);
                            }
                            break;
                        case 2:
                            tvSmsCode3.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode3.setSelected(true);
                            } else {
                                tvSmsCode3.setSelected(false);
                            }
                            break;
                        case 3:
                            tvSmsCode4.setText(s1);
                            if (currentLength >= i) {
                                tvSmsCode4.setSelected(true);
                            } else {
                                tvSmsCode4.setSelected(false);
                            }
                            break;
                    }
                    if (s.length() == 4) {
                        hideKeyboard(editSmsCode);
                        btnSubmit.setEnabled(true);
                    }else{
                        btnSubmit.setEnabled(false);
                    }
                }
            }
        });
        editSmsCode.setText(null);
    }

    @Override
    protected void initData() {
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_sms_code_1:
            case R.id.tv_sms_code_2:
            case R.id.tv_sms_code_3:
            case R.id.tv_sms_code_4:
                showTvSmsCodeSoftInput();
                break;
            case R.id.tv_count_down:
                getCode();
                break;
            case R.id.btn_submit:
                switch (type){
                    case 1:
                        submit();
                        break;
                    case 2:
                        codeVerify();
                        break;
                    case 3:
                        changePhone();
                        break;
                }
                break;
            case R.id.tv_phone_not_available:
                PhoneAppealActivity.start(this);
                break;
        }
    }

    private void codeVerify(){
        Map data = new HashMap<>();
        data.put("mobile", phone);
        data.put("code", editSmsCode.getText().toString());
        data.put("smsType", smsType);
        data.put("smsID", originalSmsId);
        LLHttpManager.codeVerify(this, data, new HttpCallback<HttpData<Void>>(this){

            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                //验证老手机号成功后，带上原originalSmsId去输入新手机号
                EnterNewPhoneActivity.start(getContext(), phone, originalSmsId, type);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void changePhone(){
        Map data = new HashMap<>();
        data.put("phone", phone);
        data.put("code", editSmsCode.getText().toString());
        data.put("smsType", smsType);
        data.put("smsId", smsId);
        data.put("originalSmsId", originalSmsId);
        LLHttpManager.changePhone(this, data, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                toast(R.string.change_phone_success);
                AppApplication.getInstance().setPhone(phone);
                AppApplication.getInstance().logoutToLogin();
//                        Intent intent = new Intent(getContext(), SettingActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void submit(){
        Map data = new HashMap<>();
        data.put("contactPhone", getIntent().getStringExtra("oldPhone"));
        data.put("accountPhone", phone);
        data.put("code", editSmsCode.getText().toString());
        data.put("content", getIntent().getStringExtra("description"));
        data.put("contentExtension", getIntent().getStringExtra("accountInfo"));
        data.put("smsID", smsId);
        LLHttpManager.createAccountQuestion(this, data, new HttpCallback<HttpData<Void>>(this){

            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                if(AppApplication.getInstance().getLoginInfo() != null){
                    startActivity_SingleTask(AccountManagerActivity.class);
                }else{
                    startActivity_SingleTask(LoginActivity.class);
                }
                toast(R.string.phone_appeal_submitted_hint);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void getCode(){
        Map<String, Object> data = new HashMap<>();
        data.put("mobile", phone);
        if(type == 1){
            LLHttpManager.aftersalesSendSms(this, data, new HttpCallback<HttpData<SmsBean>>(this){
                @Override
                public void onStart(Call call) {
                }

                @Override
                public void onEnd(Call call) {
                    hideDialog();
                }

                @Override
                public void onSucceed(HttpData<SmsBean> data) {
                    if(data.isRequestSucceed()){
                        toast(R.string.sms_code_send);
                        smsId = data.getData().getSmsID();
                        //开始倒计时
                        startCountDown();
                    }
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }
            });
        }else{
            data.put("smsType", smsType);
            LLHttpManager.sendSms(this, data, new HttpCallback<HttpData<SmsBean>>(this){
                @Override
                public void onStart(Call call) {
                    showDialog();
                }

                @Override
                public void onSucceed(HttpData<SmsBean> data) {
                    if(data.isRequestSucceed()){
                        toast(R.string.sms_code_send);
                        switch (type){
                            case 2:
                                originalSmsId = data.getData().getSmsID();
                                break;
                            case 3:
                                smsId = data.getData().getSmsID();
                                break;
                        }
                        //开始倒计时
                        startCountDown();
                    }
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    hideDialog();
                }
            });
        }
    }

    private void showTvSmsCodeSoftInput() {
        editSmsCode.requestFocus();
        showKeyboard(editSmsCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
    }
}